<template>
  <div class="containers">
    <div class="nolisdt" v-if="isEmpty">
      <text class="empty-car-tips">暂无数据</text>
    </div>
    <div class="mainborder" else>
      <div class="titleh2">
        <h2></h2>
        <h1 class="maintitles">小胖科技数据概况</h1>
        <p class="houres">
          <span>{{this.today | dateFmt }}</span>
          <span>{{this.time}}</span>
        </p>
      </div>
      <div class="main">
        <div class="top">
          <div class="topleft">
            <div class="tiptitle">销售数据总览</div>          
            <div id="myCharts" :style="{width: '100%', height: '70%'}" ref="myEchart"></div>
              <div class="baifenb">
             <span
              :class="this.goodlist.addAmount>'0'?'red':'green'"
              > 销售额环比  {{this.goodlist.addAmount}}%</span>              
              <span
             :class="this.goodlist.addNumber>'0'?'red':'green'"
              >销售量环比  {{this.goodlist.addNumber}}%</span>
              <span
              :class="this.goodlist.addUserNumber>'0'?'red':'green'"
              >用户环比  {{this.goodlist.addUserNumber}}%</span>
            </div>
          </div>
          <div class="topcenter">
            <p class="title2">今日销售额</p>
            <p class="money">
            <span  v-for="(item,index) in arr" :key="index" ><count-to :start-val="0" :end-val="item " :duration="3000" /></span>
            <span>元</span>
            </p>
            <p class="title2">今日销售数量</p>
            <p class="money">
             <span  v-for="(items,index) in arrnum" :key="index" ><count-to :start-val="0" :end-val="items " :duration="3000" /></span>
             <span>个</span>
            </p>
          </div>
          <div class="topright">
            <div class="tiptitle">今日机器销售排行榜</div>
            <div class="tablemain">
              <div class="titletip">
                <p>机器地址</p>
                <p>机器编号</p>
                <p>销售额</p>
                <p>销售数量</p>
              </div>
              <div
                class="titlemain titles"
                v-for="(item,index) in this.goodlist.vendorSaleRankList"
                :key="index"
                :class="item.yestodayPayAmount<item.todayPayAmount?'red':'green'"
              >
                <div class="titlelist one">
                  <p>
                  <marquee direction="left">{{item.positionName}}</marquee>
                  </p>
                  <p>{{item.verdorId}}</p>
                  <p>
                    {{item.todayPayAmount}}
                    <span v-if="item.yestodayPayAmount<item.todayPayAmount">
                      <img src="/static/images/上升箭头.png" alt>
                    </span>
                    <span v-if="item.yestodayPayAmount>item.todayPayAmount">
                      <img src="/static/images/下降.png" alt>
                    </span>
                  </p>
                  <p>
                    {{item.todaySaleNumber}}
                    <span v-if="item.yestodayPayAmount<item.todayPayAmount">
                      <img src="/static/images/上升箭头.png" alt>
                    </span>
                    <span v-if="item.yestodayPayAmount>item.todayPayAmount">
                      <img src="/static/images/下降.png" alt>
                    </span>
                  </p>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="bottom">
          <div class="bottomleft">
            <div class="tiptitle">交易信息</div>
            <div class="tablemain">
              <div class="titletip">
                <p>订单编号</p>
                <p>机器地址</p>
                <p>订单金额</p>
                <p>订单商品</p>
                <p>商品数量</p>
              </div>
              <div class="titlemain">
                <div
                  class="titlelist one"
                  v-for="(items,index) in list"
                  :key="index"
                  ref="rollul"
                  :class="{anim:animate==true}"
                  style="color:#fff ;"
                >
                  <p>{{items.orderId}}</p>
                  <p>{{items.positionName}}</p>
                  <p>{{items.saleAmount}}</p>
                  <p>{{items.productName}}</p>
                  <!-- <p> <marquee direction=left>{{items.productName}}</marquee></p> -->
                  <p>{{items.productNumber}}</p>
                </div>
              </div>
            </div>
          </div>
          <div class="bottomright">
            <div class="tiptitle">今日畅销商品销售量TOP3</div>
            <div id="myChart" :style="{width: '100%', height: '80%'}" ref="myEchart"></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import Chart from "echarts";
import { setInterval } from 'timers';
import store from '@/store/index'
import {
    getToken
} from '@/utils/auth';
import CountTo from 'vue-count-to'
export default {
  data() {
    return {
      today: "", //日期
      isEmpty: false, //购物车是否为空
      animate: true, //第一行显示红色
      totalData: [],
      goodlist: {},
      hours: [],
      mlists: [],
      productnames: [],
      todatnume: [],
      itemName: [],
      yesterdayAmount: [],
      todayAmount: [],
      animate: true,
      list: [],
      myCharts: null,
      year: "",
      month: "",
      date: "",
      hh: "",
      mm: "",
      nowTime: "",
      number: [],
      arr: [],
      arrnum: [],
      addAmount: [], //柱状图的比例
      itemNames: [],
      todaynum: []
    };
  },
  components: {
    CountTo
  },
  mounted() {
    
    if(this.timer){ //整个页面刷新
      clearInterval(this.timer);
    }else{
      this.timer=setInterval(()=>{
  this.websocketclose()
         this.initWebSocket()
      },60000)
    }
     
  },
  created() {
  
    const weekDay = [  //获取日期
      "星期天",
      "星期一",
      "星期二",
      "星期三",
      "星期四",
      "星期五",
      "星期六"
    ];
    this.today = new Date();//日期 
    this.time = weekDay[this.today.getDay()]; //星期几
    this.initWebSocket(); //页面刚进入时开启长连接

    setInterval(this.scroll, 2000);//向上轮播
    
     if (store.getters.token) {//从store中获取token
     
         this.token =getToken()      // 让每个请求携带token--['X-Token']为自定义key 请根据实际情况自行修改
    }
  },
 
  methods: {
    initWebSocket() {
   
      let authToken = encodeURI(this.token);
      (this.websock = new WebSocket(
        "ws://120.79.194.99:8003/managerapi/finance/daysaledata?authToken=" +
          authToken
        // "ws://192.168.0.133:8003/managerapi/finance/daysaledata?authToken=" +
        //   authToken
      )),
        (this.websock.onopen = this.websocketonopen),
        (this.websock.onmessage = this.websocketonmessage);
      this.websock.onclose = this.websocketclose;
        // alert("start");
    },

    websocketonopen() {},
    websocketonmessage(res) { //数据接收
        // alert(res);
     
      const result = JSON.parse(res.data);
      console.log(result);
      this.goodlist = result.data;
    
      this.arr=[]  //今日销售额
      var str = this.goodlist.todayAmount + "";
      for (var i = 0; i < str.length; i++) {
        var str01 = str.substr(i, 1);
        this.arr.push(str01);
      }
     
      this.arrnum=[] //今日销售数量
      var str = this.goodlist.todayNumber + "";
      for (var i = 0; i < str.length; i++) {
        var str02 = str.substr(i, 1);
        this.arrnum.push(str02);
      }

      // 调用Object.keys  判断是否还有数据，没有显示暂无数据
      const goodlist = Object.keys(this.goodlist);
      if (goodlist.length === 0 || goodlist.length == null) {
        this.isEmpty = true;
        return;
      }
      this.isEmpty = false;
      this.list = this.goodlist.vendorDetailList;
      //第二次调用前清空数组
      this.itemName = [];
      this.yesterdayAmount = [];
      this.todayAmount = [];
      this.addAmount = [];
      //柱状图的数组
      this.goodlist.reportItemVoList.forEach(item => {
        this.itemName.push(item.itemName);
        this.yesterdayAmount.push(item.yesterdayAmount);
        this.todayAmount.push(item.todayAmount);
        this.addAmount.push(item.addAmount);
        this.lineChart();
      });

      this.itemNames = [];
      this.todaynum = [];
      //柱状图的数组
      this.goodlist.productSaleRankList.forEach(item => {
        this.itemNames.push(item.productName);
        this.todaynum.push(item.todaySaleNumber);
        this.lineCharts();
      });
    },

    //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    onbeforeunload() {
      websocketclose();
    },
    websocketclose(e) {
      console.log("断开连接", e);
    },
    //向上轮播
    scroll() {
      let con1 = this.$refs.rollul;
      this.animate = !this.animate;
      var that = this; // 在异步函数中会出现this的偏移问题，此处一定要先保存好this的指向
      setTimeout(function() {
        that.list.push(that.list[0]);
        that.list.shift();
        that.animate = !that.animate; // 这个地方如果不把animate 取反会出现消息回滚的现象，此时把ul 元素的过渡属性取消掉就可以完美实现无缝滚动的效果了
      }, 0);
    },

    lineChart() {
      // console.log(this.itemName)
      this.myCharts = this.$echarts.init(document.getElementById("myCharts"));
      var option1 = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: "shadow" // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        legend: {
          data: ["昨日数据", "今日数据"],
          text: "折线图堆叠",
          x: "right",
          textStyle: {
            fontWeight: "normal", //标题颜色
            color: "#fff"
          }
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true
        },
        color: ["#4bef30", "#f22626"],
        xAxis: [
          {
            type: "category",
            data: this.itemName,
            //设置轴线的属性
            axisLine: {
              lineStyle: {
                color: "#fff",
                // width: 2 //这里是为了突出显示加上的
              }
            }
          }
        ],
        yAxis: [
          {
            type: "value",
            axisLine: {
              lineStyle: {
                color: "#fff",
                // width: 2 //这里是为了突出显示加上的
              }
            },
              //坐标轴内线的样式
               splitLine: {
                   lineStyle: {
                       color: '#222',
                       //type:'dashed'虚线
                   }
               }
          }
        ],
        series: [
          {
            name: "昨日数据",
            type: "bar",
            barWidth: 30,
             barGap:'50%',/*多个并排柱子设置柱子之间的间距*/
  	               barCategoryGap:'80%',/*多个并排柱子设置柱子之间的间距*/
            label: {
              normal: {
                show: true,
                position: "top"
              }
            },
   
            data: this.yesterdayAmount
          },

          {
            name: "今日数据",
            type: "bar",
            barWidth: 30,
            label: {
              normal: {
                show: true,
                position: "top"
              }
            },
  
            data: this.todayAmount
          },
         
        ]
      };

      // 使用刚指定的配置项和数据显示图表。
      this.myCharts.setOption(option1);
      window.addEventListener("resize", () => {
        myCharts.resize();
      });
    },
    lineCharts() {
      let myChart = this.$echarts.init(document.getElementById("myChart"));

      var option = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: "shadow" // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        // color:["#fd1c1c","#fcdf5e"],

        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true
        },
        xAxis: [
          {
            type: "category",
            data: this.itemNames,
            axisLine: {
              lineStyle: {
                color: "#fff",
                width: 2 //这里是为了突出显示加上的
              }
            }
          }
        ],
        yAxis: [
          {
            type: "value",
              //坐标轴内线的样式
               splitLine: {
                   lineStyle: {
                       color: '#222',
                       //type:'dashed'虚线
                   }
               },
            axisLine: {
              lineStyle: {
                color: "#fff",
                width: 2 //这里是为了突出显示加上的
              }
            }
          }
        ],
        series: [
          {
               name: "销售量",
            type: "bar",
            barWidth: 30,
            data: this.todaynum,
            itemStyle: {
              normal: {
                // 随机显示
                // color:function(d){return "#"+Math.floor(Math.random()*(256*256*256-1)).toString(16);}

                // 定制显示（按顺序）
                color: function(params) {
                  var colorList = ["#fcdf5e", "#62eb4e", "#f22626"];
                  return colorList[params.dataIndex];
                }
          
                
              }
            },
            label: {
              normal: {
                show: true,
                position: "top"
              }
            }
          }
        ]
      };

      // 使用刚指定的配置项和数据显示图表。
      myChart.setOption(option);
      //自适应
      window.addEventListener("resize", () => {
        myChart.resize();
      });
    }
  },

  destroyed() {
    //销毁定时器
      clearInterval(this.timer);
    
  }
};
</script>
<style lang="less" scoped>
span{
  border: none
}
.baifenb {
  margin-bottom: 10px;
  margin-top:15px;
 
  font-size: 14px;
  span {
    margin-left: 20px;
  }
}
.red {
  color: #ff0000 !important;
}
.green {
  color: #4bef30 !important;
}
@import "../../style/FinanciaSalesData/index.less";
</style>
